package clickhousedemo;

import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import ru.yandex.clickhouse.BalancedClickhouseDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class Demo01 {
    public static void main(String[] args) {
        DataSource dataSource = new BalancedClickhouseDataSource("");
        Connection conn = DataSourceUtils.getConnection(dataSource);
        String sql = "";
        Map<String, Object> params = new HashMap<>(2);
        SqlParameterSource sqlParameterSource = new MapSqlParameterSource(params);
        RowMapper<Map<String, Object>> rowMapper = new ColumnMapRowMapper();
        ChJdbcTemplate template = new ChJdbcTemplate(dataSource);
        PreparedStatementCreator psc = template.getPreparedStatementCreator(sql, sqlParameterSource);
        RowMapperResultSetExtractor rse = new RowMapperResultSetExtractor<>(rowMapper);
        ResultSet rs = null;
        try {
            PreparedStatement ps = psc.createPreparedStatement(conn);
            rs = ps.executeQuery();
            int rowNum = 0;
            List<Map<String, Object>> list = new LinkedList<>();
            while (rs.next()) {
                Map<String, Object> row = rowMapper.mapRow(rs, rowNum++);
                list.add(row);
                if (rowNum > 500) {
                    //500条数据处理一次
                    list.clear();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResultSet(rs);
            DataSourceUtils.releaseConnection(conn, dataSource);
        }
    }
}
